<template>
  <a-tree
    :tree-data="tree"
    v-model:expandedKeys="expandedKeys"
    v-model:selectedKeys="selectedKeys"
    :field-names="fieldNames"
    @select="treeSelect"
  />
</template>

<script>
import get from 'lodash-es/get.js';
import { handleCommonRes } from '@gis/lib/utils/resolver.js';
import { useUserInfoStore } from '@gis/lib/pinia/userInfo.js';
import { netTree } from '@gis/lib/api/index.js';

export default {
  name: 'net-order-room-tree',
  props: {
    modelValue: { type: [String, Number], default: undefined },
  },
  data() {
    return {
      fieldNames: {
        children: 'nodes',
        title: 'text',
        key: 'id',
      },
      tree: [],
      expandedKeys: [],
      selectedKeys: [],
    };
  },
  created() {
    // 有默认值取默认
    if (this.modelValue) {
      this.selectedKeys = [this.modelValue];
    }
    this.getTreeData();
  },
  methods: {
    treeSelect(selectedKeys) {
      let chooseId = get(selectedKeys, '[0]', '');
      if (chooseId.includes('.')) {
        return false;
      }
      this.$emit('update:modelValue', chooseId);
    },
    // 根据子节点，找到父亲节点
    findParentNode(tree, childId) {
      // 遍历树节点
      for (let node of tree) {
        // 如果当前节点就是目标节点的父节点，直接返回当前节点id
        if (node.nodes && node.nodes.some((child) => child.id === childId)) {
          return node.id;
        }
        // 否则继续遍历当前节点的子节点
        if (node.nodes) {
          const parentId = this.findParentNode(node.nodes, childId);
          if (parentId !== null) {
            return parentId;
          }
        }
      }
      // 如果没有找到父节点，则返回null
      return null;
    },
    // 处理数据，只有网约房能选择
    setSelectable(tree) {
      for (let node of tree) {
        node.selectable = node.id.includes('.') ? false : true;
        if (node.nodes && node.nodes.length) {
          this.setSelectable(node.nodes);
        }
      }
      return tree;
    },
    async getTreeData() {
      const data = await handleCommonRes(netTree, { area_code: this.area_code });
      this.tree = this.setSelectable(data);
      // 有默认值取默认值，没有默认值取返回数组的第一个值
      if (this.modelValue) {
        let parentNode = this.findParentNode(this.tree, this.modelValue);
        if (parentNode) {
          this.expandedKeys = [parentNode];
        }
      } else {
        // 取第一个网约房
        function firstNode(tree) {
          if (!tree || !tree.length) return '';
          for (let node of tree) {
            if (node.nodes && node.nodes.length) {
              return node;
            }
          }
          return null;
        }
        let first = firstNode(this.tree);
        if (first) {
          this.expandedKeys = [first.id];
          this.selectedKeys = [first.nodes[0].id];
          this.$emit('update:modelValue', get(this.selectedKeys, '[0]', ''));
        }
      }
    },
  },
  setup() {
    const { area_code } = useUserInfoStore();
    return { area_code };
  },
};
</script>

<style scoped lang="less"></style>
